package com.yuanfeng.base.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuanfeng.base.dto.*;
import com.yuanfeng.base.entity.BaseFloorAdpageEntity;
import com.yuanfeng.base.mapper.*;
import com.yuanfeng.base.service.MarketIndexService;
import com.yuanfeng.base.vo.GoodsIdsQueryListVO;
import com.yuanfeng.base.vo.MerchantFloorAdpageVO;
import com.yuanfeng.base.vo.WebFloorAdpageNameVO;
import com.yuanfeng.base.vo.WebShopListQueryResultVO;
import com.yuanfeng.base.vo.index.*;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.constant.RedisConstants;
import com.yuanfeng.commoms.dto.goods.WebGoodsListQueryDTO;
import com.yuanfeng.commoms.dto.shop.WebShopListQueryDTO;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.excel.Constants;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.DealerApplyInfoVO;
import com.yuanfeng.commoms.vo.goods.GdsListQueryResultVO;
import com.yuanfeng.commoms.vo.goods.GoodsCatVO;
import com.yuanfeng.commoms.vo.goods.GoodsIdsVO;
import com.yuanfeng.commoms.vo.goods.SecordNameListVO;
import com.yuanfeng.commoms.vo.goodscat.GoodsCatSearchChildVO;
import com.yuanfeng.commoms.vo.goodscat.WebCatMenuVO;
import com.yuanfeng.commoms.vo.shop.ShopAllBaseDistrictVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName MarketIndexServiceImpl
 * @Description 批发市场
 * @Author cyp
 * @Date 2023/6/16 13:55
 * @Version 1.0
 */
@Service
public class MarketIndexServiceImpl implements MarketIndexService {
    @Autowired
    private BaseSystemPlatformNavMapper baseSystemPlatformNavMapper;
    @Autowired
    private BaseSysConfigsMapper baseSysConfigsMapper;
    @Autowired
    private WebIndexMapper webIndexMapper;
    @Autowired
    private BaseFloorAdpageMapper baseFloorAdpageMapper;
    @Autowired
    private BaseDealerApplyInfoMapper baseDealerApplyInfoMapper;
    @Autowired
    private WebIndexServiceImpl webIndexServiceImpl;
    @Autowired
    private BaseDistrictMapper baseDistrictMapper;
    @Autowired
    private BaseDistrictServiceImpl baseDistrictServiceimpl;

    @Override
    public ResponseResult queryIndex() {
        WebIndexQueryVO result = new WebIndexQueryVO();

        // 查询首页导航
        List<WebSystemPlatformNavVO> platformNav = baseSystemPlatformNavMapper.selectPlatformNav(CommonType.ShopType.SUPPLY_SHOP.getCode());
        // 轮播
        WebSystemConfigQueryDTO param = new WebSystemConfigQueryDTO();
        param.setConfigType("supply_index_slider");
        List<WebSystemConfigQueryVO> indexSlides = baseSysConfigsMapper.selectByParam(param);
        // 轮播下广告
        WebSystemConfigQueryDTO adParam = new WebSystemConfigQueryDTO();
        adParam.setConfigType("supply_pc_index_ad");
        List<WebSystemConfigQueryVO> indexSlidesAds = baseSysConfigsMapper.selectByParam(adParam);

        // 查询一级分类
        WebGoodsCatQueryDTO catQueryParam = new WebGoodsCatQueryDTO();
        catQueryParam.setCatId(0);
        List<GoodsCatVO> goodsCats = webIndexMapper.selectByParam(catQueryParam);
        for (GoodsCatVO goodsCatResult : goodsCats) {
            List<SecordNameListVO> secordNameList = webIndexMapper.selectByCatParentId(goodsCatResult.getCatId());
            goodsCatResult.setSecordNameList(secordNameList);
        }

        // 热搜词
        List<WabSystemConfigHallVO> slides = baseSysConfigsMapper.selectByConfigType("supply_search");
        String hotWordsStr = slides.get(0).getConfigValue();
        List<String> hotWords = JsonUtils.StringToList3(hotWordsStr);

        result.setPlatformNav(platformNav);
        result.setIndexSlides(indexSlides);
        result.setGoodsCats(goodsCats);
        result.setHotWords(hotWords);
        result.setIndexSlidesAds(indexSlidesAds);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryAllAdpageFloor(UserTokenBeanDTO userTokenBean) {
        List<BaseFloorAdpageEntity> entityList = baseFloorAdpageMapper.selectList(new LambdaQueryWrapper<BaseFloorAdpageEntity>()
                .eq(BaseFloorAdpageEntity::getFloorType, CommonType.storeType.SUPPLIER_STORE.getCode()));
        /**
         * 封装数据
         */
        List<MerchantFloorAdpageVO> allFloorAdpages = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(entityList)) {
            allFloorAdpages = entityList.stream().map(entity -> {
                MerchantFloorAdpageVO catResult = new MerchantFloorAdpageVO();

                BeanUtils.copyProperties(entity, catResult);
                return catResult;
            }).collect(Collectors.toList());
        }
        for (MerchantFloorAdpageVO allFloorAdpage : allFloorAdpages) {
            // 获取楼层名称
            WebFloorAdpageNameDTO floorAdpageNameNew = JsonUtils.string2Obj(allFloorAdpage.getFloorAdpageName(),WebFloorAdpageNameDTO.class);
            allFloorAdpage.setFloorAdpageNameNew(floorAdpageNameNew);
            // 获取轮播图
            List<Integer> goodsIdList2 = JsonUtils.StringToList2(allFloorAdpage.getLeftAdpageBanner());
            List<GoodsIdsQueryListVO> adpageBannerList = webIndexMapper.selectByGoodIds2(goodsIdList2);
            allFloorAdpage.setAdpageBannerList(adpageBannerList);
            // 获取左侧广告
            List<PlatformLeftAdpageNavDTO> leftAdpageNavList = JsonUtils.string2Obj(allFloorAdpage.getLeftAdpageNav(), List.class, PlatformLeftAdpageNavDTO.class);
            allFloorAdpage.setLeftAdpageNavList(leftAdpageNavList);
            // 获取右侧热门推荐
            PlatformRightAdpageNavDTO rightRec = JsonUtils.string2Obj(allFloorAdpage.getRightHotRecommend(),PlatformRightAdpageNavDTO.class);
            allFloorAdpage.setRightRec(rightRec);
            // 设置的商品数量
            Integer goodsNum = 8;
            List<Integer> rightAdpageNavGoodsIds = JsonUtils.StringToList2(rightRec.getRightAdpageNavGoodsId());
            List<GoodsIdsVO> rightRecGoodsList = webIndexMapper.selectDelayByGoodIds(JsonUtils.StringToList2(rightRec.getRightAdpageNavGoodsId()));

            UserInfoVO userInfo = null;
            if(StringUtils.isNotBlank(userTokenBean.getToken())) {
                String userInfoStr = RedisUtil.get(RedisConstants.FKGOU_USER_TOKEN_USER + userTokenBean.getToken());
                if(StringUtils.isNotBlank(userInfoStr)){
                    userInfo = JsonUtils.toBean(userInfoStr, UserInfoVO.class);
                }
            }

            if(null == userInfo) {
                // 用户未登录
                for (GoodsIdsVO goods : rightRecGoodsList) {
                    goods.setOperateType2(goods);
                }
            }else{
                // 获取所有商品店铺信息
                List<Integer> goodsShopIdList = rightRecGoodsList.stream().map(GoodsIdsVO::getShopId).distinct().collect(Collectors.toList());
                // 查询登录用户已申请经销商成功的店铺id
                List<DealerApplyInfoVO> dealerApplyInfoList =  baseDealerApplyInfoMapper.queryDealerApplyListByShop(userInfo.getShopId(),goodsShopIdList);
                if(!org.springframework.util.CollectionUtils.isEmpty(dealerApplyInfoList)) {
                    goodsShopIdList = dealerApplyInfoList.stream().map(DealerApplyInfoVO::getSupplierShopId).distinct().collect(Collectors.toList());
                    for (GoodsIdsVO goods : rightRecGoodsList) {
                        // 商品无需申请经销商
                        if (null != goods.getSellCheck() && goods.getSellCheck().intValue() == 2) {
                            goods.setOperateType(goods.getSellDeliver());
                        } else {
                            if (!goodsShopIdList.contains(goods.getShopId())) {
                                goods.setOperateType(CommonType.supplierGoodsStatus.APPLY.getCode());
                            } else {
                                goods.setOperateType(goods.getSellDeliver());
                            }
                        }
                    }
                }else{
                    for (GoodsIdsVO goods : rightRecGoodsList) {
                        goods.setOperateType2(goods);
                    }
                }
            }

            allFloorAdpage.setRightRecGoodsList(rightRecGoodsList);
            // 获取右侧分类广告
            allFloorAdpage.setRightAdpageNavList(JsonUtils.string2Obj(allFloorAdpage.getRightAdpageNav(), List.class,WebFloorAdpageNameVO.class));

        }
        return ResponseResult.success(allFloorAdpages);
    }

    @Override
    public ResponseResult queryGoodsListFilter(WebGoodsListQueryDTO param) throws IllegalAccessException {
        // 获取分类id
        GoodsCatSearchChildVO goodsCatSearchChild;
        List<WebCatMenuVO> allMenu ;
        List<Integer> catIds;

        if (null != param.getCatId()) {

            // 从缓存中获取
            String cacheCatIds = RedisUtil.get(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + param.getCatId());
            if (null != cacheCatIds && !cacheCatIds.equals("")) {
                goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
                catIds = goodsCatSearchChild.getCatIds();
            } else {
                allMenu = webIndexMapper.selectAllCat2();
                catIds = webIndexServiceImpl.getMenuList(allMenu, param.getCatId());
                goodsCatSearchChild = new GoodsCatSearchChildVO();
                goodsCatSearchChild.setAllMenu(allMenu);
                goodsCatSearchChild.setCatIds(catIds);
                RedisUtil.set(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + param.getCatId(),JsonUtils.toString(goodsCatSearchChild),RedisUtil.EXRP_MONTH);
            }

            if (!org.springframework.util.CollectionUtils.isEmpty(catIds)) {
                catIds.add(param.getCatId());
                param.setCatIds(catIds);
                param.setCatId(0);
            }
        }
        // 查询商品列表
        Map data = ParseMapUtils.beanToMap(param);
        //分页查询数据
        IPage<GdsListQueryResultVO> page = webIndexMapper.queryBrandList(new Query<GdsListQueryResultVO>().getPage(data),param);
        List<GdsListQueryResultVO> goodsList = page.getRecords();

        //获取登录用户信息
        UserInfoVO userInfo = null;
        if(StringUtils.isNotBlank(param.getToken())) {
            userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.getToken());
        }
        if(null == userInfo) {
            // 用户未登录
            for (GdsListQueryResultVO goods : goodsList) {
                goods.setOperateType2(goods);
            }
        }else{
            // 获取所有商品店铺信息
            List<Integer> goodsShopIdList = goodsList.stream().map(GdsListQueryResultVO::getShopId).distinct().collect(Collectors.toList());
            // 查询登录用户已申请经销商成功的店铺id
            List<DealerApplyInfoVO> dealerApplyInfoList =  baseDealerApplyInfoMapper.queryDealerApplyListByShop(userInfo.getShopId(),goodsShopIdList);
            if(null != dealerApplyInfoList && dealerApplyInfoList.size() > 0 ){
                goodsShopIdList = dealerApplyInfoList.stream().map(DealerApplyInfoVO::getSupplierShopId).distinct().collect(Collectors.toList());
            }
            for(GdsListQueryResultVO goods : goodsList){
                // 商品无需申请经销商
                if(goods.getSellCheck() != null && goods.getSellCheck() == 2){
                    goods.setOperateType(goods.getSellDeliver());
                }else{
                    if(null != dealerApplyInfoList && dealerApplyInfoList.size() > 0 && !goodsShopIdList.contains(goods.getShopId())){
                        goods.setOperateType(CommonType.supplierGoodsStatus.APPLY.getCode());
                    }else{
                        goods.setOperateType(goods.getSellDeliver());
                    }
                }
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("goodsList",goodsList);
        resultMap.put("totalCount",PageUtils.getPage(page).getTotalCount());

        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult queryShopListFilter(WebShopListQueryDTO param) throws IllegalAccessException {
        if(null != param.getDistrictId()) {
            // 获取省市信息
            List<ShopAllBaseDistrictVO> allMenu = baseDistrictMapper.selectAllDistrict();
            List<Integer> districtList = baseDistrictServiceimpl.getDistrictList(allMenu, param.getDistrictId());
            param.setDistrictList(districtList);
        }
        Map data = ParseMapUtils.beanToMap(param);
        //分页查询数据
        IPage<WebShopListQueryResultVO> page = webIndexMapper.selectShopListFilter(new Query<WebShopListQueryResultVO>().getPage(data),param);
        List<WebShopListQueryResultVO> shopList = page.getRecords();

        if (!org.springframework.util.CollectionUtils.isEmpty(shopList)) {
            for (WebShopListQueryResultVO shopListQueryResult : shopList) {
                Integer shopId = shopListQueryResult.getShopId();
                // 查询店铺商品
                List<GdsListQueryResultVO> commonList = webIndexMapper.selectSupplierGoodsByShopId(shopId);
                shopListQueryResult.setCommonList(commonList);
            }
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("shopList",shopList);
        resultMap.put("totalCount",PageUtils.getPage(page).getTotalCount());
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult queryPlatformNav() {
        WebPlatformNavResultVO result = new WebPlatformNavResultVO();
        // 查询首页导航
        List<WebSystemPlatformNavVO> platformNav = baseSystemPlatformNavMapper.selectPlatformNav(CommonType.ShopType.SUPPLY_SHOP.getCode());
        // 热搜词
        List<WabSystemConfigHallVO> slides = baseSysConfigsMapper.selectByConfigType("supply_search");
        String hotWordsStr = slides.get(0).getConfigValue();
        List<String> hotWords = JsonUtils.StringToList3(hotWordsStr);
        result.setHotWords(hotWords);
        result.setPlatformNav(platformNav);
        return ResponseResult.success(result);
    }
}
